/*
 * Copyright (C) 2009 Christoph Caks
 *
 * This file is part of GLWAK.
 *
 * GLWAK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * GLWAK is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with GLWAK.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 *  Created on: 20.06.2009
 *      Author: Christoph Caks
 */

#ifndef _LOG_CPP_
#define _LOG_CPP_

#include "Log.h"
#include <cstdio>
#include "boost/thread.hpp"

namespace glwak {
namespace util {

template <typename OutputPolicy>
TLogLevel Log<OutputPolicy>::reportingLevel = logDEBUG4;

template <typename OutputPolicy>
Log<OutputPolicy>::Log() {
}

template <typename OutputPolicy>
TLogLevel &Log<OutputPolicy>::getReportingLevel() {
	return reportingLevel;
}

template <typename OutputPolicy>
std::ostringstream& Log<OutputPolicy>::getLogger( TLogLevel level ) {
	// TODO time logging
	timeval tm;
	int res = gettimeofday( &tm, NULL );
	if ( res == 0 ) {
		struct tm *timeinfo = localtime( &(tm.tv_sec) );
		char buffer [80];
		strftime( buffer, 80, "%Y-%m-%d %H:%M:%S.", timeinfo );
		char ubuffer [6];
		sprintf( ubuffer, "%6d", (int) tm.tv_usec );
		os << "- " << buffer << ubuffer;
	}
	else {
		os << "- "<< "time error";
	}
	os << " " << formatLogLevel( level ) << ": ";
	os << "[ " << boost::this_thread::get_id() << " ] ";
	// os << std::string(level > logDEBUG ? 0 : level - logDEBUG, '\t');
	messageLevel = level;
	return os;
}

template <typename OutputPolicy>
std::string Log<OutputPolicy>::formatLogLevel( TLogLevel level ) {
	   switch ( level ) {
	   case logERROR: 	return "ERROR   ";
	   case logWARNING: return "WARNING ";
	   case logINFO: 	return "INFO    ";
	   case logDEBUG:	return "DEBUG   ";
	   case logDEBUG1: 	return "DEBUG1  ";
	   case logDEBUG2: 	return "DEBUG2  ";
	   case logDEBUG3: 	return "DEBUG3  ";
	   case logDEBUG4: 	return "DEBUG4  ";
	   }
	return "LOG-ERR ";
}

template <typename OutputPolicy>
Log<OutputPolicy>::~Log() {
	if ( messageLevel <= Log::getReportingLevel() ) {
		os << std::endl;
		OutputPolicy::output( os.str() );
	}
}

} // namespace util
} // namespace glwak

#endif // _LOG_CPP_
